<script setup>
import API from "@/request/axios";
import {onMounted, reactive} from "vue";
import {infoStore} from "@/store";
import router from "@/router";
import {useRouter} from "vue-router";

const store = infoStore()
const {updateIsLogin} = store
const state = reactive({
    userInfo: []
})
const userRouter = useRouter()
const backToHome = function () {
    userRouter.push('/')
}

async function checkStatus(key) {
    const res = await API({
        url: `/login/qr/check?key=${key}&timestamp=${Date.now()}`,
    })
    return res.data
}

async function getLoginStatus(cookie = '') {
    const res = await API({
        url: `/login/status?timestamp=${Date.now()}`,
        method: 'post',
        data: {
            cookie,
        },
    })
    state.userInfo = JSON.stringify(res.data, null, 2)
    localStorage.setItem('userInfo', state.userInfo)
}

async function login() {
    let timer
    let timestamp = Date.now()
    const cookie = localStorage.getItem('cookie')
    await getLoginStatus(cookie)
    const res = await API({
        url: `/login/qr/key?timestamp=${Date.now()}`,
    })
    const key = res.data.data.unikey
    const res2 = await API({
        url: `/login/qr/create?key=${key}&qrimg=true&timestamp=${Date.now()}`,
    })
    document.querySelector('#qrImg').src = res2.data.data.qrimg

    timer = setInterval(async () => {
        const statusRes = await checkStatus(key)
        if (statusRes.code === 800) {
            alert('二维码已过期,请重新获取')
            clearInterval(timer)
        }
        if (statusRes.code === 803) {
            // 这一步会返回cookie
            clearInterval(timer)
            alert('授权登录成功')
            await getLoginStatus(statusRes.cookie)
            localStorage.setItem('cookie', statusRes.cookie)
            updateIsLogin(true)
            userRouter.push('/userInfo')
        }
    }, 3000)
}

onMounted(() => {
    login()
    if (localStorage.getItem('userinfo')) {
        router.push('/userInfo')
    }
})

</script>

<template>
    <div class="topBar">
        <svg aria-hidden="true" class="icon" @click="backToHome">
            <use xlink:href="#icon-zuojiantou"></use>
        </svg>
        <p>请扫描二维码登录</p>
    </div>
    <div class="qr">
        <img id="qrImg"/>
    </div>
</template>

<style lang="less" scoped>
.topBar {
    display: flex;
    align-items: center;

    .icon {
        margin: 0.2rem;
    }

    p {
        padding-left: 1.4rem;
    }
}

.qr {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}
</style>